package com.lock.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.condition
 * @ClassName:Test
 * @Description: Contidition等待与通知
 * @Author: zhangxiaoyu
 * @date 2021/1/20 14:20
 */
public class Test {

    //定义锁
    static Lock lock = new ReentrantLock();
    //获得Condition对象
    static Condition condition = lock.newCondition();
    
    //定义线程子类
    static  class  SubThread extends Thread{
        @Override
        public void run() {
            try {
                lock.lock();
                System.out.println("method lock");
                condition.await();  //等待
                System.out.println("method await");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println("method unlock");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
         SubThread t = new SubThread();
         t.start();

         //子线程启动后，会进入等待状态

        Thread.sleep(3000);

        //主线程在睡眠3秒后，唤醒子线程   需要先持有锁

        try {
            lock.lock();
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
    
}
